// pages/working_place/working_place.js
const app = getApp(), core = require('../../utils/core'), util = require('../../utils/util'), WeValidator = require('../../utils/we-validator'), QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js'),
mapsdk = new QQMapWX({
  key: app.globalData.mapSdkKey
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    position: true,
    location: {},
    //areas: [],
    selectedItems: null,
    isAdd: true,
    address: '',
    workAddress:null,
    houseNumber:''
  },
  bindOpen() {
    wx.openSetting();
    this.bindClose()
  },
  bindClose() {
     this.setData({
      position: true
     })
  },

  //2023-03-09新增-地图定位
  workMap(){
    let page = this;
    //获取定位
    wx.getLocation({
      success: res => {
       wx.chooseLocation({
          latitude: res.latitude,
          longitude: res.longitude,
          success:res2=>{
           console.log(res2);
           if(res2.errMsg=='chooseLocation:ok'){
            page.setData({
              workAddress:res2
            })
           }else{
            wx.showToast({
              title: '选择失败',
              icon:'none'
            })
           }
            
          },
          fail:res2=>{
            wx.showToast({
              title: '选择失败',
              icon:'none'
            })
          }
        })
      },
      fail: res => {
        console.log(res)
        page.setData({position:false});
      }
    });
  },

  onLoad: function (options) {
    this.getOpenerEventChannel().on('locationTransfer', location => {
      this.setData({
        location,
        selectedItems:[location.province, location.city, location.district],
        isAdd: false
      });
	});
	// util.getAreasTree(3,false).then(items => {
	// 	this.setData({areas: items});
	//   });
  },
  // bindDistrictChange: function (event) {
  //   let items = event.detail.items;
  //   this.setData({
  //     selectedItems: items,
  //     'location.province_id': items[0].id, 'location.province': items[0],
  //     'location.city_id': items[1].id, 'location.city': items[1],
  //     'location.district_id': items[2].id, 'location.district': items[2],
  //   });
  // },
  bindInputHouseNumber: function (event) {
    this.setData({
      'houseNumber': event.detail.value
    })
  },
  bindSave: function () {
    let workAddress = this.data.workAddress;
    if(workAddress.errMsg !=='chooseLocation:ok'){
      wx.showToast({
        title: '工作地址错误',
        icon:'none'
      })
      return false;
     }
     let data = {
       lat: workAddress.latitude,
       lng: workAddress.longitude,
       address_name: workAddress.name,
       address: workAddress.address,
       house_number: this.data.houseNumber
    }
    let that = this;
     //解析出省市区-为了匹配我们的地区库
     mapsdk.reverseGeocoder({
      sig: app.globalData.mapSdkSk,
      /**
       //String格式
        location: '39.984060,116.307520',
      */
      location: workAddress.latitude+','+workAddress.longitude, //获取表单传入的位置坐标,不填默认当前位置,示例为string格式
      //get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
      success: function(res) { //成功后的回调
        if(res.status==0 && res.message == 'Success'){
            let province = res.result.address_component.province;
            let city = res.result.address_component.city;
			let district = res.result.address_component.district;
			data['province'] = province;
			data['city'] = city;
			data['district'] = district;
            that.postAdd(data)
        }
      },
      fail: function(error) {
        console.error(error);
        that.postAdd(data)
      }
    })
  },
  postAdd(data){
    let validator = new WeValidator({
      rules: {
        //district_id: {required:true},
        address: {required:true},
        house_number:{required:true}
      },
      messages: {
        //district_id: {required:'请选择地区'},
        address: {required:'请填写详细地址'},
        house_number:{required:"请填写门牌号"}
      }
    });
    let that = this;
    if(!validator.checkData(data)) {
      return;
    }
    core.post({url: '/xilujob.company_address/add_address',data:data,success(ret, data) {
      if(that.data.isAdd) {
        that.getOpenerEventChannel().emit('locationAdd', ret.data);
      }else {
        that.getOpenerEventChannel().emit('locationEdit', ret.data);
      }
      wx.navigateBack();
    }});
  }
});
